<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="护理等级" prop="levelName">
        <el-input
          v-model="queryParams.levelName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status"
         placeholder="请选择"
         clearable
         @keyup.enter="handleQuery"
         style="width: 200px"
        >
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['serve:level:add']"
        >新增护理等级</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="levelList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="护理等级名称" align="center" prop="levelName" />
      <el-table-column label="执行护理计划" align="center" prop="planName"></el-table-column>
      <el-table-column label="护理费用(元/月)" align="center" prop="nursingFee" />
      <el-table-column label="等级说明" align="center" prop="levelDescription" width="180">
        <template #default="scope">
          <div class="level-description-cell">{{ scope.row.levelDescription }}</div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['serve:level:edit']"
            :disabled="scope.row.isUsedByElderly"
          >修改</el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['serve:level:remove']"
            :disabled="scope.row.isUsedByElderly"
          >删除</el-button>
        <el-button 
      link 
      :type="scope.row.status === 1 ? 'danger' : 'success'" 
      @click="handleToggleStatus(scope.row)" 
      v-hasPermi="['serve:level:edit']"
    >{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button>


          
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改护理等级对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="levelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="护理等级名称" prop="levelName">
          <el-input v-model="form.levelName" 
          placeholder="请输入" 
          maxlength="10"
          show-word-limit
          />
        </el-form-item>

       <el-form-item label="执行护理计划" prop="planId" required>
          <el-select v-model="form.planId" 
          placeholder="请选择"
          clearable>
            <el-option v-for="item in planOptions" :key="item.id" :label="item.planName" :value="Number(item.id)" />
          </el-select>
        </el-form-item>




        <el-form-item label="护理费用" prop="nursingFee">
          <el-input-number 
          v-model="form.nursingFee" 
          placeholder="请输入护理费用" 
          :precision="2"
          controls
          controls-position="vertical"
          :min="0"
          :step="10"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="等级说明" prop="levelDescription">
          <el-input v-model="form.levelDescription" type="textarea" 
          placeholder="请输入" 
          maxlength="50"
          show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Level">
import { listLevel, getLevel, delLevel, addLevel, updateLevel, updateLevelWithBinding } from "@/api/serve/level"
const { proxy } = getCurrentInstance()
import { listEnableNursingPlan, calculatePlanFee } from "@/api/serve/nurse"
const planOptions = ref([]); // 启用护理计划的下拉选项


// 修改：让 getEnablePlans 返回 Promise，支持链式调用
const getEnablePlans = () => {
  return listEnableNursingPlan().then(response => {
    planOptions.value = response.data; // 赋值下拉框数据源
    return response; // 可选：返回数据供后续使用
  });
};

const levelList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    levelName: null,
    status: null,
  },
  rules: {
    levelName: [
      { required: true, message: "等级名称不能为空", trigger: "blur" }
    ],
    nursingFee: [
      { required: true, message: "护理费用不能为空", trigger: "blur" },
      { type: "number", message: "请输入数字", trigger: "blur" }
    ],
    levelDescription: [
      { required: true, message: "等级说明不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态(0:禁用 1:启用)不能为空", trigger: "change" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 监听护理计划选择变化，自动计算费用
watch(() => form.value.planId, (newPlanId) => {
  if (newPlanId) {
    console.log('护理计划ID变化，开始计算费用:', newPlanId)
    calculatePlanFee(newPlanId).then(response => {
      if (response.code === 200) {
        form.value.nursingFee = response.data
        console.log('费用计算成功:', response.data)
        proxy.$modal.msgSuccess('费用自动计算完成：' + response.data + ' 元/月')
      } else {
        console.error('费用计算失败:', response.msg)
        proxy.$modal.msgError(response.msg || '费用计算失败')
      }
    }).catch(error => {
      console.error('费用计算接口调用失败:', error)
      proxy.$modal.msgError('费用计算失败，请手动输入')
    })
  } else {
    // 如果清空了护理计划选择，将费用重置为0
    form.value.nursingFee = 0.00
  }
})

/** 查询护理等级列表 */
function getList() {
  loading.value = true
  listLevel(queryParams.value).then(response => {
    levelList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    levelName: null,
    nursingFee: 0.00,
    levelDescription: null,
    creator: null,
    createTime: null,
    status: 1,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
    planId: null
  }
  proxy.resetForm("levelRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getEnablePlans(); // 新增时获取启用计划
  open.value = true
  title.value = "新增护理等级"
}

// 调整 handleUpdate 中的调用逻辑（用 .then 链式处理）
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getLevel(_id)
    .then(response => {
      form.value = response.data;
      console.log("form.planId:", form.value.planId); // 打印planId（此时需后端返回非null）
      return getEnablePlans(); // 返回Promise，继续链式调用
    })
    .then(() => {
      console.log("planOptions:", planOptions.value); // 打印下拉框数据源
      open.value = true;
      title.value = "修改护理等级";
    })
    .catch(error => {
      console.error("接口调用失败:", error);
    });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["levelRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
       // 构造包含“主表字段 + planId”的参数
        const params = {
          id: form.value.id,
          planId: form.value.planId, // 选中的护理计划ID
          levelName: form.value.levelName,
          nursingFee: form.value.nursingFee,
          levelDescription: form.value.levelDescription,
          status: form.value.status
        };
        // 调用新接口
        updateLevelWithBinding(params).then(response => {
          proxy
.$modal.msgSuccess("修改成功");
          open
.value = false;
          getList();
        });
      } else {
        addLevel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除护理等级编号为"' + _ids + '"的数据项？').then(function() {
    return delLevel(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('serve/level/export', {
    ...queryParams.value
  }, `level_${new Date().getTime()}.xlsx`)
}



/** 切换启用/禁用状态 */
function handleToggleStatus(row) {
  // 计算目标状态（1→0，0→1）
  const targetStatus = row.status === 1 ? 0 : 1;
  // 构造请求参数（仅需id和status）
  const updateParams = {
    id: row.id,
    status: targetStatus
  };
  // 调用更新接口
  updateLevel(updateParams).then(() => {
    // 提示成功并刷新列表
    proxy.$modal.msgSuccess(targetStatus === 1 ? "启用成功" : "禁用成功");
    getList();
  }).catch(() => {
    proxy.$modal.msgError(targetStatus === 1 ? "启用失败" : "禁用失败");
  });
}


getList()
</script>

<style lang="scss" scoped>
.level-description-cell {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5em;
  max-height: 3em; /* 2行的高度 */
  word-break: break-word;
}
</style>
